using UniversalAdminSystem.Application.PermissionManagement.Interfaces;
using UniversalAdminSystem.Domian.PermissionManagement.IRepository;
using UniversalAdminSystem.Domian.UserManagement.IRepository;
using UniversalAdminSystem.Domian.PermissionManagement.ValueObjects;

namespace UniversalAdminSystem.Application.PermissionManagement.Services;

/// <summary>
/// 权限检查服务实现
/// 提供用户权限验证的具体逻辑
/// </summary>
public class PermissionCheckService : IPermissionCheckService
{
    private readonly IUserRepository _userRepository;
    private readonly IRoleRepository _roleRepository;
    private readonly IPermissionRepository _permissionRepository;

    public PermissionCheckService(
        IUserRepository userRepository,
        IRoleRepository roleRepository,
        IPermissionRepository permissionRepository)
    {
        _userRepository = userRepository;
        _roleRepository = roleRepository;
        _permissionRepository = permissionRepository;
    }

    public async Task<bool> CheckUserPermissionAsync(Guid userId, string permissionCode)
    {
        try
        {
            var user = await _userRepository.GetByGuidAsync(userId);
            if (user == null || user.RoleId == null) return false;
            var role = await _roleRepository.GetByGuidAsync(user.RoleId.Value);
            if (role == null) return false;
            var permission = await _permissionRepository.GetByCodeAsync(PermissionCode.Create(permissionCode));
            if (permission == null) return false;
            
            Console.WriteLine($"检查权限: {permissionCode}");
            Console.WriteLine($"角色权限数量: {role.Permissions.Count}");
            
            // 打印角色拥有的所有权限
            foreach (var perm in role.Permissions)
            {
                Console.WriteLine($"角色权限: {perm.Code} (类型: {perm.Code.GetType().Name})");
            }
            
            // 修复比较逻辑：使用值对象比较
            var hasPermission = role.Permissions.Any(p => p.Code == PermissionCode.Create(permissionCode));
            Console.WriteLine($"权限检查结果: {hasPermission}");
            
            return hasPermission;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"权限检查错误: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 检查用户是否有任意一个指定权限
    /// </summary>
    public async Task<bool> CheckUserAnyPermissionAsync(Guid userId, IEnumerable<string> permissionCodes)
    {
        foreach (var permissionCode in permissionCodes)
        {
            if (await CheckUserPermissionAsync(userId, permissionCode)) return true;
        }
        return false;
    }

    /// <summary>
    /// 检查用户是否有所有指定权限
    /// </summary>
    public async Task<bool> CheckUserAllPermissionsAsync(Guid userId, IEnumerable<string> permissionCodes)
    {
        foreach (var permissionCode in permissionCodes)
        {
            if (!await CheckUserPermissionAsync(userId, permissionCode)) return false;
        }
        return true;
    }

    /// <summary>
    /// 获取用户的所有权限编码
    /// </summary>
    public async Task<IEnumerable<string>> GetUserPermissionsAsync(Guid userId)
    {
        try
        {   
            if (userId == Guid.Empty) throw new ArgumentException("用户ID为空", nameof(userId));
            var user = await _userRepository.GetByGuidAsync(userId) ?? throw new InvalidOperationException("用户不存在");
            if (user.RoleId == null) return Enumerable.Empty<string>();
            var role = await _roleRepository.GetByGuidAsync(user.RoleId.Value) ?? throw new InvalidDataException("用户角色不存在");
            return role.Permissions.Select(p => p.Code.Value);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取用户权限错误: {ex.Message}");
            return Enumerable.Empty<string>();
        }
    }

    /// <summary>
    /// 获取用户的所有角色
    /// </summary>
    public async Task<IEnumerable<string>> GetUserRoleAsync(Guid userId)
    {
        try
        {
            var user = await _userRepository.GetByGuidAsync(userId);
            if (user == null) return Enumerable.Empty<string>();
            if (user.RoleId == null) return Enumerable.Empty<string>();
            var role = await _roleRepository.GetByGuidAsync(user.RoleId.Value);
            if (role == null) return Enumerable.Empty<string>();
            return new[] { role.Name.Value };
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取用户角色错误: {ex.Message}");
            return Enumerable.Empty<string>();
        }
    }

    /// <summary>
    /// 检查用户是否有菜单访问权限
    /// </summary>
    public async Task<bool> CheckMenuPermissionAsync(Guid userId, string? menuPermissionCode)
    {
        // 如果菜单没有设置权限要求，则所有用户都可以访问
        if (string.IsNullOrEmpty(menuPermissionCode))
        {
            return true;
        }

        return await CheckUserPermissionAsync(userId, menuPermissionCode);
    }

    /// <summary>
    /// 检查用户是否有文件访问权限
    /// </summary>
    public async Task<bool> CheckFilePermissionAsync(Guid userId, string fileAccessLevel, Guid? fileOwnerId = null)
    {
        try
        {
            // 超级管理员可以访问所有文件
            if (await IsSuperAdminAsync(userId))
            {
                return true;
            }

            // 管理员可以访问除超级管理员文件外的所有文件
            if (await IsAdminAsync(userId))
            {
                if (fileOwnerId.HasValue)
                {
                    var fileOwner = await _userRepository.GetByGuidAsync(fileOwnerId.Value);
                    return fileOwner == null || !await IsSuperAdminAsync(fileOwnerId.Value);
                }
                return true;
            }

            // 普通用户只能访问自己的文件或公开文件
            switch (fileAccessLevel.ToLower())
            {
                case "public":
                    return true;
                case "private":
                    return fileOwnerId.HasValue && fileOwnerId.Value == userId;
                case "restricted":
                    return false;
                default:
                    return false;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"文件权限检查错误: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 检查用户是否有日志查看权限
    /// </summary>
    public async Task<bool> CheckLogPermissionAsync(Guid userId, string logLevel)
    {
        try
        {
            // 超级管理员可以查看所有日志
            if (await IsSuperAdminAsync(userId))
            {
                return true;
            }

            // 管理员可以查看除系统级日志外的所有日志
            if (await IsAdminAsync(userId))
            {
                return logLevel.ToLower() != "system";
            }

            // 普通用户只能查看基本日志
            return logLevel.ToLower() == "basic" || logLevel.ToLower() == "info";
        }
        catch (Exception ex)
        {
            Console.WriteLine($"日志权限检查错误: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 检查用户是否有系统设置管理权限
    /// </summary>
    public async Task<bool> CheckSystemSettingPermissionAsync(Guid userId, string settingKey)
    {
        try
        {
            // 超级管理员可以管理所有设置
            if (await IsSuperAdminAsync(userId))
            {
                return true;
            }

            // 管理员可以管理除系统核心设置外的所有设置
            if (await IsAdminAsync(userId))
            {
                var restrictedSettings = new[] { "system.core", "security", "database" };
                return !restrictedSettings.Any(s => settingKey.StartsWith(s));
            }

            // 普通用户只能查看基本设置
            var basicSettings = new[] { "ui", "theme", "language" };
            return basicSettings.Any(s => settingKey.StartsWith(s));
        }
        catch (Exception ex)
        {
            Console.WriteLine($"系统设置权限检查错误: {ex.Message}");
            return false;
        }
    }


    /// <summary>
    /// 检查用户是否为超级管理员
    /// </summary>
    public async Task<bool> IsSuperAdminAsync(Guid userId)
    {
        try
        {
            var permissions = await GetUserPermissionsAsync(userId);
            return permissions.Any(p => p.Contains("super") || p.Contains("system"));
        }
        catch (Exception ex)
        {
            Console.WriteLine($"超级管理员检查错误: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 检查用户是否为管理员
    /// </summary>
    public async Task<bool> IsAdminAsync(Guid userId)
    {
        try
        {
            var user = await _userRepository.GetByGuidAsync(userId);
            if (user == null || user.RoleId == null) return false;
            var role = await _roleRepository.GetByGuidAsync(user.RoleId.Value);
            if (role == null) return false;
            return role.IsSupper;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"管理员检查错误: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 获取用户可访问的菜单权限列表
    /// </summary>
    public async Task<IEnumerable<string>> GetUserMenuPermissionsAsync(Guid userId)
    {
        try
        {
            var allPermissions = await GetUserPermissionsAsync(userId);
            return allPermissions.Where(p => p.StartsWith("menu:"));
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取菜单权限错误: {ex.Message}");
            return Enumerable.Empty<string>();
        }
    }

    /// <summary>
    /// 获取用户可访问的文件权限列表
    /// </summary>
    public async Task<IEnumerable<string>> GetUserFilePermissionsAsync(Guid userId)
    {
        try
        {
            var allPermissions = await GetUserPermissionsAsync(userId);
            return allPermissions.Where(p => p.StartsWith("file:"));
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取文件权限错误: {ex.Message}");
            return Enumerable.Empty<string>();
        }
    }

    /// <summary>
    /// 获取用户可访问的日志权限列表
    /// </summary>
    public async Task<IEnumerable<string>> GetUserLogPermissionsAsync(Guid userId)
    {
        try
        {
            var allPermissions = await GetUserPermissionsAsync(userId);
            return allPermissions.Where(p => p.StartsWith("log:"));
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取日志权限错误: {ex.Message}");
            return Enumerable.Empty<string>();
        }
    }

    /// <summary>
    /// 获取用户可访问的系统设置权限列表
    /// </summary>
    public async Task<IEnumerable<string>> GetUserSystemSettingPermissionsAsync(Guid userId)
    {
        try
        {
            var allPermissions = await GetUserPermissionsAsync(userId);
            return allPermissions.Where(p => p.StartsWith("setting:"));
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取系统设置权限错误: {ex.Message}");
            return Enumerable.Empty<string>();
        }
    }
}